package com.aiju.cash.ui.pay;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.widget.TextView;
import android.widget.Toast;

import com.aiju.app.SimpleHttpCallback;
import com.aiju.base.activity.BaseTitleActivity;
import com.aiju.base.window.CustomPopWindow;
import com.aiju.bean.Discount;
import com.aiju.bean.DiscountType;
import com.aiju.cash.R;
import com.aiju.cash.core.api.DataJson;
import com.aiju.cash.core.api.DiscountApi;
import com.aiju.cash.receiver.MyReceiver;
import com.aiju.cash.ui.member.MemberSearchActivity;
import com.aiju.cash.ui.member.entity.MemberCard;
import com.aiju.cash.ui.pay.entity.Detail;
import com.aiju.cash.ui.pay.entity.Pay;
import com.aiju.cash.ui.pay.manager.PayManager;
import com.aiju.cash.ui.pay.util.AdditionMoney;
import com.aiju.cash.util.GsonHelper;
import com.aiju.cash.widgit.DiscountDialog;
import com.aiju.common.PixValue;
import com.aiju.utils.L;
import com.aiju.utils.PreferencesUtils;
import com.aiju.utils.T;
import com.aiju.utils.tts.BaiduTTSManager;
import com.google.gson.Gson;
import com.uuzuche.lib_zxing.activity.CodeUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import static com.aiju.cash.ui.good.GoodAddActivity.REQUEST_CODE;

/**
 * @author: 佐为
 * @date: 2016-11-21 13:20
 * @version: V1.0
 * @Description: 收款界面
 */
public class PayActivity extends BaseTitleActivity implements View.OnClickListener {

    /**
     * 优惠金额，应收金额
     */
    private TextView favorableTextView, receivableTextView;

    /**
     * 实时金额，总金额
     */
    private TextView timeMoneyTextView, totalMoneyTextView;

    /**
     * 键盘运算类
     */
    private AdditionMoney additionMoney;

    /**
     * 优化折扣
     */
    private View zkView, jjView;
    private TextView zkTextView, jjTextView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pay);
        setCenterTitle("收款");
        setRightTitle("选择优惠");

        additionMoney = new AdditionMoney();
        timeMoneyTextView = (TextView) findViewById(R.id.tv_pay_money_time);
        totalMoneyTextView = (TextView) findViewById(R.id.tv_pay_money_sum);
        favorableTextView = (TextView) findViewById(R.id.tv_pay_favorable);
        receivableTextView = (TextView) findViewById(R.id.tv_pay_money);
        //优惠券
        zkView = findViewById(R.id.rl_discount_zk);
        jjView = findViewById(R.id.rl_discount_jj);

        zkTextView = (TextView) findViewById(R.id.tv_discount_zk_name);
        jjTextView = (TextView) findViewById(R.id.tv_discount_jj_name);

        zkView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                findViewById(R.id.ly_favorable).setVisibility(View.GONE);
                v.setVisibility(View.GONE);
                additionMoney.removeDiscount();
            }
        });
        jjView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                findViewById(R.id.ly_favorable).setVisibility(View.GONE);
                v.setVisibility(View.GONE);
                additionMoney.removeDiscount();
            }
        });

        IntentFilter filter = new IntentFilter();
        filter.addAction(MyReceiver.MESSAGE_RECEIVED_ACTION);
        registerReceiver(myReceiver, filter);
        PayManager.setPayFrom();
        initListener();

    }

    /**
     * 初始化事件，回调
     */
    private void initListener() {
        addKeyBoardListener();
        mAiJuTitleBarView.setRightOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (totalMoneyTextView.getText().toString().equals("0.00")) {
                    T.ToastShort("请输入收款金额");
                    return;
                }
                requestDiscount();
            }
        });
        additionMoney.setMoneyChange(new AdditionMoney.OnMoneyChange() {
            @Override
            public void onMoneyChange(String favorable, String printAllMoney, String totalMoney, String receivableMoney) {
                favorableTextView.setText(favorable);
                timeMoneyTextView.setText(printAllMoney);
                totalMoneyTextView.setText(totalMoney);
                if (Double.valueOf(receivableMoney) < 0) {
                    receivableTextView.setText("0.00");
                } else {
                    receivableTextView.setText(receivableMoney);
                }
            }
        });
    }

    /**
     * 添加数字键盘点击监听
     */
    private void addKeyBoardListener() {
        ViewGroup group = (ViewGroup) findViewById(R.id.bl_number);
        int childCount = group.getChildCount();
        for (int i = 0; i < childCount; i++) {
            ViewGroup childGroup = (ViewGroup) group.getChildAt(i);
            int childGroupCount = childGroup.getChildCount();
            for (int j = 0; j < childGroupCount; j++) {
                childGroup.getChildAt(j).setOnClickListener(this);
            }
        }
    }

    @Override
    protected void onDestroy() {
        unregisterReceiver(myReceiver);
        super.onDestroy();
    }

    /**
     * 后台推送
     */
    private BroadcastReceiver myReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String extras = intent.getStringExtra("extras");
            String massage = intent.getStringExtra("message");
            DataJson dataJson = null;
            try {
                JSONObject jsonObject = new JSONObject(extras);
                dataJson = new DataJson(jsonObject.getString("json"));
            } catch (JSONException e) {
                e.printStackTrace();
            }
            if (dataJson.isSuccess()) {
                String data = dataJson.getData().toString();
                if (data.equals("payment_0")) {
                    //starPaySussecc();
                } else if (data.equals("payment_1")) {
                    //starPaySussecc();
                } else if (data.equals("payment_2")) {
                    starPaySussecc();
                } else if (data.equals("payment_3")) {
                    // starPaySussecc();
                } else if (data.equals("invite")) {
                    //T.ToastShort("邀请店员");
                } else if (data.equals("unbind")) {
                    //T.ToastShort("删除店员");
                }
            }
        }

    };

    private void requestDiscount() {
        new DiscountApi(mDialogHelper).list(new SimpleHttpCallback() {
            @Override
            protected void onDataSuccess(String data) {
                List<DiscountType> discountTypes = GsonHelper.convertEntities(data, DiscountType.class);
     /*           if (Util.isEmpty(discountTypes)) {
                    T.ToastShort("没有可选的优惠折扣");
                    return;
                }*/

                PreferencesUtils.putString(PayActivity.this, "money", totalMoneyTextView.getText().toString());
                new DiscountDialog(PayActivity.this)
                        .setLayoutParams()
                        .setOnClickDiscount(new DiscountDialog.OnClickDiscount() {
                            @Override
                            public void onDiscount(Discount discount, String msg) {
                                if (!checkDiscount(discount)) {
                                    T.ToastShort("所选优惠条件不适用");
                                    return;
                                }
                                findViewById(R.id.ly_favorable).setVisibility(View.VISIBLE);
                                if (discount.getType() == 1 || discount.getType() == 4) {
                                    zkView.setVisibility(View.VISIBLE);
                                    zkTextView.setText(msg);
                                    jjView.setVisibility(View.GONE);
                                } else {
                                    jjView.setVisibility(View.VISIBLE);
                                    jjTextView.setText(msg);
                                    zkView.setVisibility(View.GONE);
                                }
                                discount.setName(msg);
                                additionMoney.addDiscount(discount);

                            }

                            @Override
                            public void onCard(View view) {
                                selectMember();
                            }
                        })
                        .setDiscountList(discountTypes)
                        .show();
            }
        });
    }

    /**
     * 检查优惠券
     */
    private boolean checkDiscount(Discount discount) {
        Double total = Double.valueOf(totalMoneyTextView.getText().toString());
        if (discount.getType() == 3 || discount.getType() == 4) {
            if (total < Double.valueOf(discount.getCondition())) {
                return false;
            }
        } else if (discount.getType() == 2) {
            if (total < Double.valueOf(discount.getValue())) {
                return false;
            }
        }
        return true;
    }

    /**
     * 选择会员
     */
    private void selectMember() {
        Intent intent = new Intent(this, MemberSearchActivity.class);
        intent.putExtra("type", MemberSearchActivity.SELECT_MEMVER);
        startActivityForResult(intent, 100);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_pay_0:
                additionMoney.onKeyDown(0);
                break;
            case R.id.tv_pay_1:
                additionMoney.onKeyDown(1);
                break;
            case R.id.tv_pay_2:
                additionMoney.onKeyDown(2);
                break;
            case R.id.tv_pay_3:
                additionMoney.onKeyDown(3);
                break;
            case R.id.tv_pay_4:
                additionMoney.onKeyDown(4);
                break;
            case R.id.tv_pay_5:
                additionMoney.onKeyDown(5);
                break;
            case R.id.tv_pay_6:
                additionMoney.onKeyDown(6);
                break;
            case R.id.tv_pay_7:
                additionMoney.onKeyDown(7);
                break;
            case R.id.tv_pay_8:
                additionMoney.onKeyDown(8);
                break;
            case R.id.tv_pay_9:
                additionMoney.onKeyDown(9);
                break;
            case R.id.tv_pay_point:
                additionMoney.onKeyDown(AdditionMoney.POINT);
                break;
            case R.id.tv_pay_c:
                additionMoney.onKeyDown(AdditionMoney.CLEAR);
                break;
            case R.id.tv_pay_pay:
                //additionMoney.onKeyDown(AdditionMoney.PAY);
                pay(v);
                break;
            case R.id.iv_pay_back:
                additionMoney.onKeyDown(AdditionMoney.BACK);
                break;
            case R.id.iv_pay_add:
                additionMoney.onKeyDown(AdditionMoney.ADD);
                break;

            case R.id.tv_pay_qr:
                if (!mUser.getShop().isWx() && !mUser.getShop().isAlipay()) {
                    T.ToastShort("您尚未签约任何三方支付，请联系客服");
                    return;
                }
                if (filter) {
                    T.ToastShort("应收金额为0元，请选择现金收款");
                    return;
                }
                Intent intent = new Intent(PayActivity.this, PayQRCodeActivity.class);
                intent.putExtra("price", receivableTextView.getText().toString());
                intent.putExtra("type", PayQRCodeActivity.SHOW_QR);
                startActivity(intent);
                break;
            case R.id.tv_pay_wechat:
                payName = "微信成功收款";
                if (!mUser.getShop().isWx()) {
                    T.ToastShort("您尚未签约微信支付，请联系客服");
                    return;
                }
                if (filter) {
                    T.ToastShort("应收金额为0元，请选择现金收款");
                    return;
                }
                startPayZhiFBaoActivity(1);
                break;
            case R.id.tv_pay_money:
                Intent moneyIntent = new Intent(PayActivity.this, PayMoneyActivity.class);
                Bundle moneyBundle = new Bundle();
                moneyBundle.putSerializable("pay", getPay());
                moneyIntent.putExtras(moneyBundle);
                startActivity(moneyIntent);
                break;
            case R.id.tv_pay_zhif:
                payName = "支付宝成功收款";
                if (!mUser.getShop().isAlipay()) {
                    T.ToastShort("您尚未签约支付宝，请联系客服");
                    return;
                }
                if (filter) {
                    T.ToastShort("应收金额为0元，请选择现金收款");
                    return;
                }
                startPayZhiFBaoActivity(0);
                break;
        }
    }

    private String payName;

    /**
     * 扫描支付
     *
     * @return
     */
    private void startPayZhiFBaoActivity(int type) {
        Intent zhifIntent = new Intent(PayActivity.this, PayZhiFBaoActivity.class);
        Bundle zhifBundle = new Bundle();
        zhifBundle.putSerializable("pay", getPay());
        zhifBundle.putInt("type", type);
        zhifIntent.putExtras(zhifBundle);
        startActivity(zhifIntent);
    }

    /**
     * 付款商品信息
     *
     * @return
     */
    private Pay getPay() {
        //应收
        String receivablePrice = receivableTextView.getText().toString();
        //原价格
        String totalPrice = totalMoneyTextView.getText().toString();
        //优惠
        String favorablePrice = favorableTextView.getText().toString();

        Detail detail = new Detail();
        detail.setGoodsName("无码商品");
        detail.setNum("1");
        detail.setPrice(totalPrice);
        detail.setUnit("件");
        detail.setSum(totalPrice);

        List<Detail> details = new ArrayList<>();
        details.add(detail);

        String detailString = new Gson().toJson(details);

        Pay pay = new Pay();
        pay.setStoreId(mUser.getShop().getStoreId());
        pay.setPrice(receivablePrice);
        pay.setActualPrice(receivablePrice);//实付
        pay.setSumPrice(totalPrice);
        pay.setOperatorId(mUser.getOperatorId());
        pay.setOperatorName(mUser.getUserName());
        pay.setSubject("向 " + mUser.getShop().getShopName() + " 付款");
        pay.setShouldPrice(receivablePrice);//应付
        pay.setChangePrice("0");
        pay.setRoundPrice("0");
        pay.setPrivPrice(favorablePrice);
        pay.setMemberPhone(additionMoney.getMemberPhone());
        if (additionMoney.getDiscount() != null) {
            pay.setPrivType(additionMoney.getDiscount().getName());
        } else {
            pay.setPrivType("无");
        }
        pay.setDetail(detailString);

        return pay;
    }

    private boolean filter;

    /**
     * 支付界面
     */
    private void pay(View view) {
        if (totalMoneyTextView.getText().equals("0.00")) {
            T.ToastShort("请输入金额");
            return;
        }
        if (additionMoney.getDiscount() != null && !checkDiscount(additionMoney.getDiscount())) {
            T.ToastShort("所选优惠条件不适用");
            return;
        }
        if (receivableTextView.getText().equals("0.00")) {
            filter = true;
        } else {
            filter = false;
        }
//初始化
        final ScaleAnimation scaleAnimation = new ScaleAnimation(1f, 1.3f, 1f, 1.3f,
                Animation.RELATIVE_TO_SELF, 1f, Animation.RELATIVE_TO_SELF, 0.5f);
        scaleAnimation.setDuration(500);
        findViewById(R.id.ly_pay_money).startAnimation(scaleAnimation);

        View contentView = LayoutInflater.from(this).inflate(R.layout.pop_list, null);
        //处理popWindow 显示内容
        handleListView(contentView);
        //创建并显示popWindow
        new CustomPopWindow.PopupWindowBuilder(this)
                .setView(contentView)
                .setAnimationStyle(R.style.dialogStyle)
                .size(ViewGroup.LayoutParams.MATCH_PARENT, PixValue.dp.valueOf(238))//显示大小
                .create()
                .showAtLocation(view, Gravity.BOTTOM, 0, 0);

    }

    private void handleListView(View contentView) {
        contentView.findViewById(R.id.tv_pay_money).setOnClickListener(this);
        contentView.findViewById(R.id.tv_pay_qr).setOnClickListener(this);
        contentView.findViewById(R.id.tv_pay_zhif).setOnClickListener(this);
        contentView.findViewById(R.id.tv_pay_wechat).setOnClickListener(this);
    }

    /**
     * 跳转支付成功
     */
    private void starPaySussecc() {
        L.d("Lifecycle", "payActivity");
        Intent intent = new Intent(PayActivity.this, PaySuccessActivity.class);
        intent.putExtra("money", receivableTextView.getText().toString());
        PayManager.setPayFrom();

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                BaiduTTSManager.getInstance().speak(payName + receivableTextView.getText().toString() + "元");
            }
        });
        L.d("payActivity 语音播报");
        L.d(payName + receivableTextView.getText().toString() + "元");

        startActivity(intent);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        /**
         * 处理二维码扫描结果
         */
        if (requestCode == REQUEST_CODE) {
            //处理扫描结果（在界面上显示）
            if (null != data) {
                Bundle bundle = data.getExtras();
                if (bundle == null) {
                    return;
                }
                if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                    String result = bundle.getString(CodeUtils.RESULT_STRING);
                    Toast.makeText(this, "解析结果:" + result, Toast.LENGTH_LONG).show();
                } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
                    Toast.makeText(PayActivity.this, "解析二维码失败", Toast.LENGTH_LONG).show();
                }
            }
        }

        if (requestCode == 100) {
            if (null != data) {
                MemberCard memberCard = (MemberCard) data.getSerializableExtra("memberCard");
                if (memberCard != null) {
                    Discount discount = new Discount();
                    discount.setValue(memberCard.getDiscount());
                    if (!TextUtils.isEmpty(memberCard.getType()) && memberCard.getType().equals("3")) {
                        discount.setType(2);
                        zkView.setVisibility(View.VISIBLE);
                        zkTextView.setText("会员积分抵扣" + discount.getValue() + "元");
                        jjView.setVisibility(View.GONE);
                        discount.setName(zkTextView.getText().toString());
                    } else {
                        discount.setType(1);
                        jjView.setVisibility(View.VISIBLE);
                        jjTextView.setText("会员" + discount.getValue() + "折");
                        zkView.setVisibility(View.GONE);
                        discount.setName(jjTextView.getText().toString());
                    }
                    discount.setMemberPhone(memberCard.getMemberPhone());
                    additionMoney.addDiscount(discount);
                    additionMoney.setMemberPhone(discount.getMemberPhone());
                    findViewById(R.id.ly_favorable).setVisibility(View.VISIBLE);
                } else {
                    jjView.setVisibility(View.GONE);
                    zkView.setVisibility(View.GONE);
                    additionMoney.setMemberPhone(data.getStringExtra("memberPhone"));
                    additionMoney.addDiscount(null);
                }
            }
        }
    }
}
